package com.chris.cc.user.service.impl;

import com.chris.cc.common.exception.InvalidArgumentException;
import com.chris.cc.user.config.MD5PasswordEncoder;
import com.chris.cc.user.mapper.UserMapper;
import com.chris.cc.user.model.dto.UserDto;
import com.chris.cc.user.model.entity.User;
import com.chris.cc.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * Copyright (c) 2018-2025, chris All rights reserved.
 * <p>
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * <p>
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * <p>
 * Author: haoka (haokang207@126.com)
 * <p>
 * Date: 2018/8/20 14:33
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User add(UserDto user) throws InvalidArgumentException {
        User u = User.builder()
                .email(user.getEmail())
                .deptId(user.getDeptId())
                .enable(user.getEnable())
                .name(user.getName())
                .password(MD5PasswordEncoder.encode(user.getPassword()))
                .tel(user.getTel())
                .build();
        u.setModifyDate(new Date());
        u.setCreateDate(new Date());
        try {
            userMapper.insert(u);
        } catch (DuplicateKeyException e) {
            throw new InvalidArgumentException("手机号码已存在", user.getTel());
        }
        return u;
    }

    @Override
    public Page<User> query(Long deptId, Boolean enable, String keyword, Pageable page) {
        Example e = new Example(User.class);
        Example.Criteria criteria = e.createCriteria();
        if (deptId != null) {
            criteria.andEqualTo("deptId", deptId);
        }
        if (enable != null) {
            criteria.andEqualTo("enable", enable);
        }
        if (StringUtils.isNotBlank(keyword)) {
            Example.Criteria or = e.createCriteria();
            or.orLike("name", "%" + keyword + "%");
            or.orLike("tel", "%" + keyword + "%");
            e.and(or);
        }
        RowBounds rowBounds = new RowBounds(Long.valueOf(page.getOffset()).intValue(), page.getPageSize());
        List<User> list = userMapper.selectByExampleAndRowBounds(e, rowBounds);
        //屏蔽密码到前台
        list.forEach(u -> u.setPassword(null));
        int total = userMapper.selectCountByExample(e);
        return new PageImpl<>(list, page, total);
    }

    @Override
    public User toggle(Long userId, Boolean enable) {
        if (userId == null || enable == null) {
            return null;
        }
        User u = User.builder()
                .userId(userId)
                .enable(enable)
                .build();
        u.setModifyDate(new Date());
        userMapper.updateByPrimaryKeySelective(u);
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public User update(UserDto user) throws InvalidArgumentException {
        if (user.getUserId() == null) {
            return null;
        }
        User u = User.builder()
                .userId(user.getUserId())
                .enable(user.getEnable())
                .email(user.getEmail())
                .name(user.getName())
                .password(user.getPassword() != null ? MD5PasswordEncoder.encode(user.getPassword()) : null)
                .tel(user.getTel())
                .build();
        u.setModifyDate(new Date());
        try {
            userMapper.updateByPrimaryKeySelective(u);
        } catch (DuplicateKeyException e) {
            throw new InvalidArgumentException("手机号码已存在", user.getTel());
        }
        return userMapper.selectByPrimaryKey(user.getUserId());
    }

    @Override
    public User getByTel(String tel) {
        if (StringUtils.isBlank(tel)) {
            return null;
        }
        return userMapper.selectOne(User.builder().enable(true).tel(tel).build());
    }

    /**
     * 根据id获取用户
     *
     * @param id
     * @return
     */
    @Override
    public User get(Long id) {
        if (id == null) {
            return null;
        }
        return userMapper.selectByPrimaryKey(id);
    }
}
